#include "gl_widget.h"

GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent) {
    m_skyBox = new SkyBox();
}

GLWidget::~GLWidget() {
    makeCurrent();
    delete m_skyBoxProgram;
    doneCurrent();
    delete m_skyBox;
}

void GLWidget::initializeGL() {
    initializeOpenGLFunctions();

    glClearColor(0.f, 0.f, 0.f, 1.f);
    m_skyBoxProgram = new SkyBoxShaderProgram(":/glsl/sky_box.vert"
                                              , ":/glsl/sky_box.frag");
    m_skyBoxProgram->setAttribute(m_skyBoxProgram->getAttrPosition()
                                  , m_skyBox->getComponentSize()
                                  , m_skyBox->getStride()
                                  , 0);
    m_skyBoxDrawer = new SkyBoxDrawer(m_skyBoxProgram, m_skyBox);
}

void GLWidget::resizeGL(int w, int h) {
    QMatrix4x4 projM;
    projM.setToIdentity();
    projM.perspective(45.f, (float)w/h, 1, 10);

    QMatrix4x4 viewM;
    viewM.setToIdentity();
    viewM.lookAt(QVector3D(0.f, 1.2f, 5.f)
                 , QVector3D(0.f, 0.f, 0.f)
                 , QVector3D(0.f, 1.f, 0.f));

    QMatrix4x4 vpM = projM * viewM;
    m_skyBoxDrawer->setMatrix(vpM);
}

void GLWidget::paintGL() {
    glClear(GL_COLOR_BUFFER_BIT);
    m_skyBoxProgram->bind();
    m_skyBoxDrawer->draw();
}

